package com.blog4j.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog4j.api.client.FeignUser;
import com.blog4j.api.vo.SystemBaseConfigVo;
import com.blog4j.api.vo.UserIllegalRecordVo;
import com.blog4j.api.vo.UserInfoVo;
import com.blog4j.common.constants.CommonConstant;
import com.blog4j.common.enums.ErrorEnum;
import com.blog4j.common.enums.UserIllegalTypeEnum;
import com.blog4j.common.exception.Blog4jException;
import com.blog4j.common.utils.CommonUtil;
import com.blog4j.contentVerify.context.ContentVerifyContext;
import com.blog4j.contentVerify.context.VerifyResult;
import com.blog4j.contentVerify.enums.TextServiceEnum;
import com.blog4j.contentVerify.enums.VerifyResultEnum;
import com.blog4j.contentVerify.enums.VerifyTypeEnum;
import com.blog4j.contentVerify.model.TextVerifyModel;
import com.blog4j.contentVerify.processor.VerifyProcessor;
import com.blog4j.system.entity.BarrageEntity;
import com.blog4j.system.mapper.BarrageMapper;
import com.blog4j.system.service.BarrageService;
import com.blog4j.system.service.SystemService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 98k灬
 * @version v1.0.0
 * @Description : 功能描述
 * @Create on : 2024/8/18 10:49
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class BarrageServiceImpl extends ServiceImpl<BarrageMapper, BarrageEntity>
            implements BarrageService {
    private final SystemService systemService;
    private final FeignUser feignUser;
    private final VerifyProcessor verifyProcessor;

    /**
     * 弹幕留言
     *
     * @param barrage 留言信息
     */
    @Override
    public BarrageEntity addBarrage(BarrageEntity barrage) {
        SystemBaseConfigVo systemConfig = systemService.getBaseSystemConfig();
        String userId = "";
        try {
            userId = StpUtil.getLoginIdAsString();
        } catch (Exception exception) {
            log.warn("user not login.");
        }

        // 检查留言是否合法
        if (!checkBarrage(barrage.getMessageContent())) {
            if (StringUtils.isNotBlank(userId)) {
                UserIllegalRecordVo recordVo = UserIllegalRecordVo.builder()
                        .createTime(CommonUtil.getCurrentDateTime())
                        .illegalType(UserIllegalTypeEnum.ILLEGAL_BARRAGE.getType())
                        .userId(userId)
                        .build();
                feignUser.addUserIllegalRecord(recordVo);
            }
            throw new Blog4jException(ErrorEnum.ILLEGAL_BARRAGE_ERROR);
        }

        if (StringUtils.isBlank(userId)) {
            barrage.setUserAvatar(systemConfig.getUserDefaultAvatar());
        } else {
            UserInfoVo userInfoVo = feignUser.getUserInfoByUserId(userId);
            if (StringUtils.isBlank(userInfoVo.getUserId())) {
                throw new Blog4jException(ErrorEnum.USER_NOT_EXIST_ERROR);
            }
            barrage.setUserAvatar(userInfoVo.getAvatar());
        }
        barrage.setCreateTime(CommonUtil.getCurrentDateTime());
        this.baseMapper.insert(barrage);
        return barrage;
    }

    private boolean checkBarrage(String content) {
        if (StringUtils.isBlank(content)) {
            return true;
        }
        VerifyResult verifyResult = this.getBarrageVerifyResult(content);
        // 获取阿里云内容审核接口失败 重试三次
        if (!verifyResult.getStatus()) {
            try {
                int retryTime = 0;
                while(retryTime < CommonConstant.DEFAULT_RETRY_TIMES) {
                    verifyResult = this.getBarrageVerifyResult(content);
                    if (verifyResult.getStatus()) {
                        break;
                    }
                    ThreadUtil.sleep(CommonConstant.DEFAULT_RETRY_INTERVAL_TIME);
                    retryTime += 1;
                }

                if (!verifyResult.getStatus()) {
                    // 重试了三次还是调用失败
                    return false;
                }
            } catch (Exception exception) {
                log.error("checkBarrage error .");
                throw new Blog4jException(ErrorEnum.SYSTEM_ERROR);
            }
        }

        return !(verifyResult.getResult() == VerifyResultEnum.REJECT);
    }

    private VerifyResult getBarrageVerifyResult(String content) {
        TextVerifyModel textVerifyModel = new TextVerifyModel();
        textVerifyModel.setTextContent(content);
        textVerifyModel.setTextService(TextServiceEnum.COMMENT_DETECTION.getService());
        ContentVerifyContext verifyContext = ContentVerifyContext.builder()
                .verifyType(VerifyTypeEnum.TEXT)
                .textVerifyModel(textVerifyModel)
                .build();
        verifyProcessor.contentVerify(verifyContext);
        return verifyContext.getVerifyResult();
    }
}
